package com.fc.dao;

import com.fc.entity.User;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

@Repository("userDao")
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

    public UserDaoImpl(){

    }
    @Autowired
    public UserDaoImpl(@Qualifier("sessionFactory")SessionFactory sessionFactory){
        this.setSessionFactory(sessionFactory);
    }

    @Override
    public void save(User user) {
        super.getHibernateTemplate().save(user);
    }

    @Override
    public void delete(User user) {

    }

    @Override
    public void update(User user) {

    }

    @Override
    public User findById(Integer id) {
        return null;
    }

    @Override
    public List<User> findByExample(User instance) {
        return null;
    }

    @Override
    public List<User> findUserByProperty(String propertyName, Object value) {
        String queryString = "from User as u where u." + propertyName + "= ?";
        return this.getHibernateTemplate().find(queryString,value);
    }

    @Override
    public List<User> findAll() {
        return this.getHibernateTemplate().find("from User");
    }

    public List<User> findByPage(final int beginIndex,final int pageSize) {
        String hql = "from User order by id";

       return this.getHibernateTemplate().execute(
                new HibernateCallback<List<User>>() {

                    @Override
                    public List<User> doInHibernate(Session session) throws HibernateException, SQLException {
                        String hql = "from User order by id";

                        Query query = session.createQuery(hql);

                        query .setFirstResult(beginIndex); // 设置获取结果的起始下标
                        query .setMaxResults(pageSize); // 设置最大返回结果数

                        return  query.list();
                    }
                }
        );
    }

}
